﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace HtmlHelper
{
    public class XhtmlRegex
    {
        public static string getAttributeName(string attributeHtml)
        {
            return Regex.Match(attributeHtml, "[^=]+").Value;
        }
        public static string getAttributeValue(string attributeHtml)
        {
            return attributeHtml.Substring(attributeHtml.IndexOf("=") + 1);
        }
        public static string getTagAttributes(string tagHtml)
        {
            string s = XhtmlRegex.getFirstTag(tagHtml);
            s= Regex.Match(s, @"\s.*(?=(>$))",RegexOptions.Singleline).Value;
            return s;
        }
        public static string[] SpliteAttributes(string Html)
        {
            List<string> list = new List<string>();
            MatchCollection matches = Regex.Matches(Html, @"[\w-:]+\s*(=\s*((""[^""]*"")|('[^']*')|([\w-/\+]+)))?");
            for (int i = 0; i < matches.Count; i++)
            {
                list.Add(matches[i].Value);
            }
            return list.ToArray();
        }
        public static string getTagName(string tagHtml)
        {
            string s= Regex.Match(tagHtml, @"(?<=(<))[^\s>]+(?=([\s>]))").Value;
            return Regex.Replace(s, "(^/)|(/$)", "",RegexOptions.Singleline);
        }
        public static string getCommentText(string commentHtml)
        {
            string s=Regex.Match(commentHtml, "(?=<(^<!--)).*(?=(>$))", RegexOptions.Singleline).Value;
            return s;
        }
        public static string geScriptText(string scriptHtml)
        {
            int i = XhtmlRegex.getFirstTag(scriptHtml).Length;
            return Regex.Match(scriptHtml.Substring(i), @".*(?=(</script>))", RegexOptions.IgnoreCase | RegexOptions.Singleline).Value;
        }
        public static string[] SpliteHtmlElement(string html)
        {
            List<string> list = new List<string>();
            MatchCollection matches = Regex.Matches(html, @"(<script.*?/script>)|(<(([^>""']*)|(""[^""]*"")|('[^']*'))*>)|([^<]+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            for (int i = 0; i < matches.Count; i++)
            {
                list.Add(matches[i].Value);
            }
            return list.ToArray();
        }
        public static string NormalizeAttributeValue(string AttributeValue)
        {
            string s = Regex.Replace(AttributeValue, @"\s+", " ");
            s = Regex.Replace(s, @"(^"")|(""$)|(^')|('$)", "");
            return s;
        }
        private static string getFirstTag(string Html)
        {
            return Regex.Match(Html, @"<(([^>""']*)|(""[^""]*"")|('[^']*'))*>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Value;
        }
    }
}
